<?php
/**
 * @author Feng
 * @date 2012-5-28
 */
class controller_admin_picture_special extends system_user_control {
	
	private $concept = null;
	public function init() {
		if(!parent::init()) {
			return ;
		}
		picture_category::$_lang = $this->user->getLang();
		$this->concept = new picture_special_localeConcept($this->user->getLang());
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Pictures'))->setRoute('picture/index'));
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Specials'))->setRoute('picture/special/index'));
	}
		
	public function action_index() {
		$this->_goRoute('picture/special/list');
		$this->render();
	}
	
	public function action_photo() {
		$render = null;
		$id = intval($this->_param('id'));
		if(!($row = $this->concept->fetch(array('special.id = ?' => $id)))) {
			throw new picture_exception("The Special is not Existing.");
		}
		$this->view->row = $row;

		$listWhere = array('photo.id IN(SELECT `photo_id` FROM `picture_special_photo` WHERE `special_id` = ?)' => $id);
		$plConcept = new picture_photo_localeConcept($this->user->getLang());
		$photo_id = array();
		if($this->getRequest()->isPost()) {
			//$this->referer = $this->_post('referer');
			try {
				if(($this->_post('batch') || $this->_post('delete')) && !$this->_post('next')) {
					$photo_id = (array) $this->_post('photo_id');
					if(empty($photo_id)) {
						throw new picture_exception("No item Selected.");
					}
					$_pid = implode(', ', $photo_id);
				}
				if($this->_post('delete')) {
					$this->_auth();
					$model = new picture_special_photo_model();
					$model->delete(array("special_id = ?" => $id, "photo_id IN($_pid)"));
					$row->updatePhotoCount();
					$this->view->throwMessage = 'Complete';
				}
				if($this->_post('batch')) {
					if(!$this->_post('next')) {
						$listWhere["photo.id IN($_pid)"] = null;
					}
					$concept = new picture_special_concept($this->user->getLang());
					$this->view->specialList = $concept->fetchAll(array("special.id = ?" => $id));
					$this->view->step = 0;
					$render = 'picture/special/photoBatchEdit.phtml';
					if($this->_post('next')) {
						foreach((array) $this->_post('photo') AS $id => $_photo) {
							if(!($row = $plConcept->fetch(array('id = ?' => $id)))) {
								continue;
							}
							try {
								system_db::getAdapter()->beginTransaction();
								$row->getLocale()->setTitle(trim($_photo['title']));
								$row->getLocale()->setDescription($_photo['description']);
								$row->setDisplayOrder(intval($_photo['display_order']));
								$row->setKeywords($_photo['tag']);
								$row->save(false);
								system_db::getAdapter()->commit();
							} catch (Exception $ex) {
								system_db::getAdapter()->rollBack();
							}
						}
						$this->view->throwMessage = 'Complete';
					}
				}
			} catch (Exception $e) {
				$this->view->throwException = $e;
			}
		}
		$this->view->checkedList = $photo_id;
		$list = $plConcept->fetchAll($listWhere, array('photo.display_order ASC'));

		$pids = $locale = $keyword = array();
		foreach($list AS $_row) {
			$pids[$_row->getId()] = $_row->getId();
		}
		if(!empty($pids)) {
			$pid = implode(', ', $pids);
			$concept = new picture_photo_locale_concept();
			foreach($concept->fetchAll(array("photo_id IN($pid)", 'lang = ?' => $this->user->getLang())) AS $_row) {
				$locale[$_row->getPhotoId()] = $_row;
			}	
			$_kw = array();		
			$concept = new resource_keyword_concept();
			foreach($concept->fetchAll(array("id IN (SELECT `keyword_id` FROM `picture_photo_keyword` WHERE `photo_id` IN($pid))")) AS $_row) {
				$_kw[$_row->getId()] = $_row->getName();
			}
			if(!empty($_kw)) {
				$pid = implode(', ', array_keys($_kw));
				$concept = new picture_photo_keyword_concept();
				foreach($concept->fetchAll(array("keyword_id IN($pid)")) AS $_row) {
					if(!isset($_kw[$_row->getKeywordId()])) continue;
					$keyword[$_row->getPhotoId()][] = $_kw[$_row->getKeywordId()];
				}
			}
		}
		$this->view->locale = $locale;
		$this->view->keyword = $keyword;
		$this->view->list = $list;
		$this->_crumbs()->addPage(system_nav_page::create($row->getLocale()->getTitle())->setRoute('picture/special/edit')->setParams(array('id' => $row->getId())));
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Photo List'))->setRoute('picture/special/photo')->setParams(array('id' => $row->getId())));
		$this->render($render);
	}
	
	public function action_addnew() {
		$row = $this->concept->create();
		$row->setIsActive(1);
		$row->setDisplayOrder(0);
		if(1 && $category_id = intval($this->_get('category_id'))) {
			$this->view->categoryList = array($category_id);
		}
		$row = $this->_saveRow($row);
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_crumbs()->addPage(system_nav_page::create($this->language('New Special'))->setRoute('picture/special/addnew'));
		$this->render('picture/special/row.phtml');
	}
	
	public function action_edit() {
		$id = intval($this->_param('id'));
		if(!($row = $this->concept->fetch(array('special.id = ?' => $id)))) {
			throw new picture_exception("The Special is not Existing.");
		}
		$categoryList = array();
		$concept = new picture_special_category_concept($this->user->getLang());
		foreach($concept->fetchAll(array('special_id = ?' => $id)) AS $_row) {
			$categoryList[] = $_row->getCategoryId();
		}
		$this->view->categoryList = $categoryList;
		$row = $this->_saveRow($row);
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_crumbs()->addPage(system_nav_page::create($row->getLocale()->getTitle())->setRoute('picture/special/edit')->setParams(array('id' => $row->getId())));
		$this->render('picture/special/row.phtml');
	}
	
	public function action_delete() {
		$id = intval($this->_param('id'));
		if(!($row = $this->concept->fetch(array('special.id = ?' => $id)))) {
			throw new picture_exception("The Special is not Existing.");
		}
		$categories = array();
		$sql = "";
		$sql .= "SELECT a.`special_id`, b.`category_id`, b.`title` FROM `picture_category_locale` AS b ";
		$sql .= "INNER JOIN `picture_special_category` AS a ON a.`category_id` = b.`category_id` ";
		$sql .= "WHERE a.`special_id` = '$id' AND b.`lang` = '{$this->user->getLang()}'";
		foreach(system_db::getAdapter()->fetchAll($sql) AS $category) {
			$categories[] = $category;
		}
		$localeList = array();
		$concept = new picture_special_locale_concept();
		foreach($concept->fetchAll(array('special_id = ?' => $id)) AS $locale) {
			$localeList[$locale->getLang()] = $locale;
		}
		if($this->getRequest()->isPost()) {
			$this->referer = $this->_post('referer');
			try {
				system_db::getAdapter()->beginTransaction();
				$this->_auth();
				$row->delete($this->_post('options'));
				system_db::getAdapter()->commit();
				$this->view->throwMessage = 'Complete';
			} catch (Exception $e) {
				system_db::getAdapter()->rollBack();
				$this->view->throwException = $e;
			}
		}
		$this->view->localeList = $localeList;
		$this->view->categories = $categories;
		$this->view->referer = $this->referer;
		$this->view->row = $row;
		$this->_crumbs()->addPage(system_nav_page::create($row->getLocale()->getTitle())->setRoute('picture/special/edit')->setParams(array('id' => $row->getId())));
		$this->_crumbs()->addPage(system_nav_page::create("Delete")->setRoute('picture/special/delete')->setParams(array('id' => $row->getId())));
		$this->render();
	}
	
	private function _saveRow($row) {
		if(!$this->getRequest()->isPost()) {
			return $row;
		}		
		$manual = $this->_post('manualKeyNameCheck');
		if(!$row->getId() && !$manual) {
			$name = system_encrypt::createIdByTime();
		} else {
			$name = trim($this->_post('name'));
		}
		$row->getLocale()->setTitle(trim($this->_post('title')));
		$row->getLocale()->setDescription($this->_post('description'));
		$this->view->manualKeyNameCheck = $manual ? true : false;
		$this->referer = $this->_post('referer');
		$this->view->categoryList = $categoryList = (array) $this->_post('category_id');
		$row->setName($name);
		$row->setDisplayOrder(intval($this->_post('display_order')));
		$row->setIsActive(intval($this->_post('is_active')) ? 1 : 0);
		$row->setIsRecommend(intval($this->_post('is_recommend')) ? 1 : 0);
		$row->setKeywords(trim($this->_post('tag')));		
		foreach($categoryList AS $cid) {
			$row->addCategoryList($cid);
		}
		$this->_saveToDatabase($row, 'cover', 'image');
		return $row;
	}
	
	public function action_list() {
		$adapter = new system_paginator_adapter_concept(new picture_special_concept($this->user->getLang()));
		$adapter->setCurrentPageNumber(intval($this->_param('page', 1)));
		
		$this->view->order = $order = strtolower($this->_get('order'));
		$this->view->searchby = $searchby = strtolower($this->_get('searchby'));
		$this->view->category_id = $category_id = intval($this->_get('category_id'));
		if($category_id) {
			$adapter->where(array('special.id IN(SELECT `special_id` FROM `picture_special_category` WHERE `category_id` = ?)' => $category_id));
		}
		$keyword = trim($this->_get('keyword'));
		if($keyword == self::$_keyword) $keyword = '';
		if($keyword) {
			$keyword = addslashes($keyword);
			$in = "SELECT `special_id` FROM `picture_special_locale` WHERE `title` LIKE '%$keyword%' AND `lang` = '{$this->user->getLang()}'";
			$adapter->where("`name` LIKE '%$keyword%' OR `id` IN($in)");
		}
		$_order = array("display_order ASC", "creationtime DESC");
		if($order) {
			$this->view->sort = $sort = intval($this->_get('sort'));
			switch($order) {
				case 'date': {
					$order = 'lastmodified';
					break;
				}
				case 'photo': {
					$order = 'ptotal';
					break;
				}
				case 'creationtime': {
					break;
				}
				default: {
					$sort = !$sort;
					$order = 'display_order';
					break;
				}
			}
			$_sort = !$sort ? 'DESC' : 'ASC';
			$_order = array("$order $_sort");
		}
		$adapter->setLimit(30);
		$adapter->order($_order);
		$list = new system_paginator($adapter);

		$sids = $categories = $keywords = array();
		foreach($list AS $row) {
			$sids[$row->getId()] = $row->getId();
		}
		if(!empty($sids)) {
			$pid = implode(', ', $sids);
			$sql = "";
			$sql .= "SELECT a.`special_id`, b.`category_id`, b.`title` FROM `picture_category_locale` AS b ";
			$sql .= "INNER JOIN `picture_special_category` AS a ON a.`category_id` = b.`category_id` ";
			$sql .= "WHERE a.`special_id` IN($pid) AND b.`lang` = '{$this->user->getLang()}'";
			foreach(system_db::getAdapter()->fetchAll($sql) AS $row) {
				$categories[$row['special_id']][] = $row;
			}
			$sql = "";
			$sql .= "SELECT a.`special_id`,a.`keyword_id`,b.`name` FROM `picture_special_keyword` AS a ";
			$sql .= "INNER JOIN `resource_keyword` AS b ON a.`keyword_id` = b.`id` ";
			$sql .= "WHERE a.`special_id` IN($pid)";
			foreach(system_db::getAdapter()->fetchAll($sql) AS $row) {
				$keywords[$row['special_id']][] = $row;
			}
		}
		
		if($this->getRequest()->isPost()) {
			try {
				foreach((array)$this->_post('display_order') AS $id => $value) {
					system_db::getAdapter()->query("UPDATE `picture_special` SET `display_order` = '$value' WHERE `id` = '$id'");
				}
				$this->view->throwMessage = 'Complete';
			} catch (Exception $e) {
				$this->view->throwException = $e;
			}
		}

		$this->view->categories = $categories;
		$this->view->keywords = $keywords;
		$this->view->list = $list;
		$this->_crumbs()->addPage(system_nav_page::create($this->language('List'))->setRoute('picture/special/list'));
		$this->render();
	}
}
